<template>
    <div class="Tool">
        <div v-for="item in toolList" :key="item.id" class="row" :class="{ active: item.id === active }"
            @click="rowClick(item)">
            <img v-if="item.icon" class="m-l-10" :src="item.icon" alt="">
            <span class="name m-l-10">{{ item.name }}</span>
        </div>
        <div class="row" @click="delAll()">
            <img class="m-l-10" :src="del.icon" alt="">
            <span class="name m-l-10">{{ del.name }}</span>
        </div>
        <div class="row" @click="onToolClearIDB()">
            <img class="m-l-10" :src="clearIDB.icon" alt="">
            <span class="name m-l-10">{{ clearIDB.name }}</span>
        </div>
    </div>
</template>

<script>
import sel from './mixins/drawTool/sel'
import point from './mixins/drawTool/point'
import line from './mixins/drawTool/line'
import polygon from './mixins/drawTool/polygon'
import circle from './mixins/drawTool/circle'
import measureLine from './mixins/drawTool/measureLine'
import measureArea from './mixins/drawTool/measureArea'
import clearIDB from './mixins/drawTool/clearIDB'
import { initLoad, callUIInteraction, addResponseEventListener } from '@/PixelStreaming/webrtcVideo.js'
export default {
    name: 'BasinChange',
    mixins: [sel, point, line, polygon, circle, measureLine, measureArea, clearIDB],
    data() {
        return {
            active: '',
            toolList: {

                point: {
                    index:0,
                    id: 'Point',
                    name: '绘制点',
                    icon: require('@/assets/map/toolIcon/point.png')
                },
                line: {
                    index:1,
                    id: 'Line',
                    name: '绘制线',
                    icon: require('@/assets/map/toolIcon/line.png')
                },
                polygon: {
                    index:2,
                    id: 'Polygon',
                    name: '绘制面',
                    icon: require('@/assets/map/toolIcon/polygon.png')
                },
                // rect: {
                //     id: 'Rect',
                //     name: '绘制矩形',
                //     icon: require('@/assets/map/toolIcon/rect.png')
                //
                // },
                // circle: {
                //     id: 'Circle',
                //     name: '绘制圆',
                //     icon: require('@/assets/map/toolIcon/circle.png')
                // },
                ml: {
                    index:3,
                    id: 'ML',
                    name: '长度测量',
                    icon: require('@/assets/map/toolIcon/ml.png')
                },
                mp: {
                    index:4,
                    id: 'MA',
                    name: '面积测量',
                    icon: require('@/assets/map/toolIcon/mp.png')
                },
                sel: {
                    index:5,
                    id: 'Sel',
                    name: '选择删除',
                    icon: require('@/assets/map/toolIcon/sel.png')
                }

            },
            del: {
                index:6,
                name: '清空标绘',
                icon: require('@/assets/map/toolIcon/del.png')
            },
            clearIDB: {
                index:7,
                id: 'clearIDB',
                name: '清理数据库',
                icon: require('@/assets/map/toolIcon/del.png')
            }

        }
    },
    created() {
        this.entitiesDrawTool = new Map()
    },
    methods: {
        delAll() {
            var param = {
                "type": 6,  //  0绘制点 1绘制线 2绘制面 3长度测量 4面积测量 5选择删除 6清空标绘 7清理数据库
                "bState": false, // 选中状态
            }
            callUIInteraction("Web_ToolBar", param);
            this.entitiesDrawTool.forEach((entity, key) => {
                this.$viewer.entities.remove(entity)
            })
            this.entitiesDrawTool.clear()

            // 删除所有测量的数据源
            var names = []
            this.$viewer.dataSources._dataSources.forEach(item => {
                if (item.name.indexOf('DrawTool') !== -1) {
                    names.push(item.name)
                }
            })
            names.forEach(item => {
                var ds = this.$viewer.dataSources.getByName(item)
                this.$viewer.dataSources.remove(ds[0], true)
            })
            this.$store.getters.eventCesiumOption.isDrawing = false
            var offSelf = `offTool${this.active}`
            this.runFn(offSelf)
            this.active = ''
        },
        runFn(fn) {
            if (Object.hasOwnProperty.call(this, fn) &&
                this[fn] instanceof Function) {
                eval(this[fn]())
            }
        },
        rowClick(item) {
            var bState;
            if (this.active === '') {
                bState = true;
                this.$store.getters.eventCesiumOption.isDrawing = true
                var on = `onTool${item.id}`
                this.runFn(on)
                this.active = item.id
            } else {
                bState = false;
                this.$store.getters.eventCesiumOption.isDrawing = false
                if (this.active === item.id) {
                    var offSelf = `offTool${item.id}`
                    this.runFn(offSelf)
                    this.active = ''
                } else {
                    var offLast = `offTool${this.active}`
                    this.runFn(offLast)
                    this.active = ''
                    this.rowClick(item)
                }
            }
            var param = {
                "type": item.index,  //  0绘制点 1绘制线 2绘制面 3长度测量 4面积测量 5选择删除 6清空标绘 7清理数据库
                "bState": bState, // 选中状态
            }
            callUIInteraction("Web_ToolBar", param);//

        },
        /**
       * 拾取位置点
       *
       * @param {Object} px 屏幕坐标
       *
       * @return {Object} Cartesian3 三维坐标
       */
        getCatesian3FromPX: function (px) {
            if (this.$viewer && px) {
                var picks = this.$viewer.scene.drillPick(px)
                var cartesian = null
                var isOn3dtiles = false; var isOnTerrain = false
                // drillPick
                for (const i in picks) {
                    const pick = picks[i]

                    if (pick &&
                        pick.primitive instanceof Cesium.Cesium3DTileFeature ||
                        pick && pick.primitive instanceof Cesium.Cesium3DTileset ||
                        pick && pick.primitive instanceof Cesium.Model) { // 模型上拾取
                        isOn3dtiles = true
                    }
                    // 3dtilset
                    if (isOn3dtiles) {
                        this.$viewer.scene.pick(px) // pick
                        cartesian = this.$viewer.scene.pickPosition(px)
                        if (cartesian) {
                            const cartographic = Cesium.Cartographic.fromCartesian(cartesian)
                            if (cartographic.height < 0) cartographic.height = 0
                            const lon = Cesium.Math.toDegrees(cartographic.longitude)
                            const lat = Cesium.Math.toDegrees(cartographic.latitude)
                            const height = cartographic.height
                            cartesian = this.transformWGS84ToCartesian({ lng: lon, lat: lat, alt: height })
                        }
                    }
                }
                // 地形
                const boolTerrain = this.$viewer.terrainProvider instanceof Cesium.EllipsoidTerrainProvider
                // Terrain
                if (!isOn3dtiles && !boolTerrain) {
                    var ray = this.$viewer.scene.camera.getPickRay(px)
                    if (!ray) return null
                    cartesian = this.$viewer.scene.globe.pick(ray, this.$viewer.scene)
                    isOnTerrain = true
                }
                // 地球
                if (!isOn3dtiles && !isOnTerrain && boolTerrain) {
                    cartesian = this.$viewer.scene.camera.pickEllipsoid(px, this.$viewer.scene.globe.ellipsoid)
                }
                if (cartesian) {
                    const position = this.transformCartesianToWGS84(cartesian)
                    if (position.alt < 0) {
                        cartesian = this.transformWGS84ToCartesian(position, 0.1)
                    }
                    return cartesian
                }
                return false
            }
        },
        /**
       * 获取84坐标的距离
       * @param {*} positions
       */
        getPositionDistance: function (positions) {
            let distance = 0
            for (let i = 0; i < positions.length - 1; i++) {
                const point1cartographic = this.transformWGS84ToCartographic(positions[i])
                const point2cartographic = this.transformWGS84ToCartographic(positions[i + 1])
                const geodesic = new Cesium.EllipsoidGeodesic()
                geodesic.setEndPoints(point1cartographic, point2cartographic)
                let s = geodesic.surfaceDistance
                s = Math.sqrt(
                    Math.pow(s, 2) +
                    Math.pow(point2cartographic.height - point1cartographic.height, 2)
                )
                distance = distance + s
            }
            return distance.toFixed(3)
        },
        /** *
       * 坐标转换 84转笛卡尔
       *
       * @param {Object} {lng,lat,alt} 地理坐标
       *
       * @return {Object} Cartesian3 三维位置坐标
       */
        transformWGS84ToCartesian(position, alt) {
            if (this.$viewer) {
                return position
                    ? Cesium.Cartesian3.fromDegrees(
                        position.lng || position.lon,
                        position.lat,
                        position.alt = alt || position.alt,
                        Cesium.Ellipsoid.WGS84
                    )
                    : Cesium.Cartesian3.ZERO
            }
        },
        /** *
       * 坐标数组转换 笛卡尔转84
       *
       * @param {Array} WSG84Arr {lng,lat,alt} 地理坐标数组
       * @param {Number} alt 拔高
       * @return {Array} Cartesian3 三维位置坐标数组
       */
        transformWGS84ArrayToCartesianArray(WSG84Arr, alt) {
            if (this.$viewer && WSG84Arr) {
                var $this = this
                return WSG84Arr
                    ? WSG84Arr.map(function (item) { return $this.transformWGS84ToCartesian(item, alt) })
                    : []
            }
        },
        /** *
       * 坐标转换 笛卡尔转84
       *
       * @param {Object} Cartesian3 三维位置坐标
       *
       * @return {Object} {lng,lat,alt} 地理坐标
       */
        transformCartesianToWGS84(cartesian) {
            if (this.$viewer && cartesian) {
                var ellipsoid = Cesium.Ellipsoid.WGS84
                var cartographic = ellipsoid.cartesianToCartographic(cartesian)
                return {
                    lng: Cesium.Math.toDegrees(cartographic.longitude),
                    lat: Cesium.Math.toDegrees(cartographic.latitude),
                    alt: cartographic.height
                }
            }
        },
        /** *
       * 坐标数组转换 笛卡尔转86
       *
       * @param {Array} cartesianArr 三维位置坐标数组
       *
       * @return {Array} {lng,lat,alt} 地理坐标数组
       */
        transformCartesianArrayToWGS84Array(cartesianArr) {
            if (this.$viewer) {
                var $this = this
                return cartesianArr
                    ? cartesianArr.map(function (item) { return $this.transformCartesianToWGS84(item) })
                    : []
            }
        },
        /**
       * 84坐标转弧度坐标
       * @param {Object} position wgs84
       * @return {Object} Cartographic 弧度坐标
       *
       */
        transformWGS84ToCartographic(position) {
            return position
                ? Cesium.Cartographic.fromDegrees(
                    position.lng || position.lon,
                    position.lat,
                    position.alt
                )
                : Cesium.Cartographic.ZERO
        }

    }
}
</script>

<style lang="scss" scoped>
.Tool {
    position: relative;
    top: 0px;
    left: 0px;
    display: flex;
    flex-direction: column;
    padding: 5px;

    .row {
        display: flex;
        align-items: center;
        cursor: pointer;
        margin-top: 3px;
        padding: 5px;

        &:hover,
        &.active {
            box-shadow: rgb(11, 234, 235) 0px 0px 8px inset;
        }

        img {
            width: 16px;
        }

        .name {
            font-size: 12px;
        }
    }
}
</style>
